package com.jinniulive.platform.module.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jinniulive.platform.MyApp;
import com.jinniulive.platform.R;
import com.jinniulive.platform.activity.MainActivity;
import com.jinniulive.platform.bean.LoginInfo;
import com.jinniulive.platform.urls.NetConfig;

import org.xutils.common.Callback;
import org.xutils.common.util.MD5;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, PlatformActionListener {

    private EditText mEditTextAccount, mEditTextPassWork;
    private ImageView mImageViewPull, mImageViewShow, mImageViewQQ, mImageViewWechat;
    private Button mButtonLogin;
    private TextView mTextViewForget, mTextViewEnroll;
    private Boolean isShowPassWork = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);
        setContentView(R.layout.activity_login);
        initView();
        autoLogin();
        setListener();
    }

    //自动登录
    private void autoLogin() {
        SharedPreferences sp = getSharedPreferences("autoLogin", MODE_PRIVATE);
        String account = sp.getString("account", "");
        String password = sp.getString("password", "");
        String userId = sp.getString("userId", "");
        String userName = sp.getString("userName", "");
        //三方自动登陆
        if (account.isEmpty() || password.isEmpty()) {
            try {
                String encode = URLEncoder.encode(userName, "UTF-8");
                String format = String.format(NetConfig.SFDL, userId, encode);
                RequestParams params = new RequestParams(format);
                login(params);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            String md5 = MD5.md5(password);
            mEditTextAccount.setText(account);
            mEditTextPassWork.setText(password);
            String format = String.format(NetConfig.DL, account, md5);
            RequestParams params = new RequestParams(format);
            login(params);
        }
    }

    private void login(RequestParams params) {
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                final LoginInfo info = gson.fromJson(result, LoginInfo.class);
                int errorcode = info.getErrorcode();
                if (errorcode == 200) {
                    MyApp app = (MyApp) getApplication();
                    app.setLoginInfo(info);
                    CountDownTimer timer = new CountDownTimer(300, 100) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                        }

                        @Override
                        public void onFinish() {

                            startActivity(new Intent(LoginActivity.this, MainActivity.class));

                        }
                    }.start();

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(LoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void setListener() {
        mButtonLogin.setOnClickListener(this);
        mImageViewPull.setOnClickListener(this);
        mImageViewShow.setOnClickListener(this);
        mTextViewForget.setOnClickListener(this);
        mTextViewEnroll.setOnClickListener(this);
        mImageViewQQ.setOnClickListener(this);
        mImageViewWechat.setOnClickListener(this);

        //监听账号
        mEditTextAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (TextUtils.isEmpty(mEditTextAccount.getText())) {
                    mEditTextPassWork.setText("");
                    mEditTextPassWork.setEnabled(false);
                } else {
                    mEditTextPassWork.setEnabled(true);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEditTextPassWork.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(mEditTextPassWork.getText())) {
                    mButtonLogin.setEnabled(false);
                    Drawable drawable = getResources().getDrawable(R.mipmap.dl1_12);
                    mButtonLogin.setBackgroundDrawable(drawable);
                } else {
                    mButtonLogin.setEnabled(true);
                    Drawable drawable = getResources().getDrawable(R.mipmap.dl_06);
                    mButtonLogin.setBackgroundDrawable(drawable);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    private void initView() {
        mEditTextAccount = (EditText) findViewById(R.id.activity_login_et_account);
        mEditTextPassWork = (EditText) findViewById(R.id.activity_login_et_passwork);
        mImageViewPull = (ImageView) findViewById(R.id.activity_login_iv_pull);
        mImageViewShow = (ImageView) findViewById(R.id.activity_login_iv_show);
        mButtonLogin = (Button) findViewById(R.id.activity_login_bt_dl);
        mTextViewForget = (TextView) findViewById(R.id.activity_login_tv_forget);
        mTextViewEnroll = (TextView) findViewById(R.id.activity_login_tv_enroll);
        mImageViewQQ = (ImageView) findViewById(R.id.activity_login_iv_qq);
        mImageViewWechat = (ImageView) findViewById(R.id.activity_login_iv_wechat);

    }

    @Override
    public void onClick(View v) {
        if (v != null) {
            switch (v.getId()) {
                //qq
                case R.id.activity_login_iv_qq:
                    QQ qq = new QQ(this);
                    login(qq);
                    break;
                //微信
                case R.id.activity_login_iv_wechat:
                    Wechat wechat = new Wechat(this);
                    login(wechat);
                    break;
                //账号下拉
                case R.id.activity_login_iv_pull:
                    break;
                //密码显示
                case R.id.activity_login_iv_show:
                    if (isShowPassWork) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.dl_09);
                        mImageViewShow.setImageDrawable(drawable);
                        mEditTextPassWork.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        isShowPassWork = false;
                    } else {
                        Drawable drawable = getResources().getDrawable(R.mipmap.dl1_09);
                        mImageViewShow.setImageDrawable(drawable);
                        mEditTextPassWork.setInputType(InputType.TYPE_CLASS_TEXT);
                        isShowPassWork = true;
                    }
                    break;
                //登录
                case R.id.activity_login_bt_dl:
                    final String account = mEditTextAccount.getText().toString().trim();
                    final String s = mEditTextPassWork.getText().toString().trim();
                    final String md5Password = MD5.md5(s);
                    String format = String.format(NetConfig.DL, account, md5Password);
                    RequestParams params = new RequestParams(format);
                    x.http().get(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            Gson gson = new Gson();
                            LoginInfo loginInfo = gson.fromJson(result, LoginInfo.class);
                            int errorcode = loginInfo.getErrorcode();
                            String codedes = loginInfo.getCodedes();
                            if (errorcode == 200) {
                                MyApp app = (MyApp) getApplication();
                                app.setLoginInfo(loginInfo);
                                SharedPreferences sp = getSharedPreferences("autoLogin", MODE_PRIVATE);
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString("account", account);
                                edit.putString("password", s);
                                edit.commit();
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();

                            } else {
                                Toast.makeText(LoginActivity.this, codedes, Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {

                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });

                    break;
                //忘记密码
                case R.id.activity_login_tv_forget:
                    startActivity(new Intent(this, ForgetPasswordActivity.class));
                    break;
                //新用户注册
                case R.id.activity_login_tv_enroll:
                    startActivity(new Intent(this, EnrollActivity.class));
                    break;
                default:
                    break;
            }
        }
    }

    private void login(Platform platform) {
        platform.setPlatformActionListener(this);
        platform.authorize();

    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

        final String userId = platform.getDb().getUserId();
        final String userName = platform.getDb().getUserName();
        try {
            String encode = URLEncoder.encode(userName, "UTF-8");
            String format = String.format(NetConfig.SFDL, userId, encode);
            RequestParams params = new RequestParams(format);
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Gson gson = new Gson();
                    LoginInfo loginInfo = gson.fromJson(result, LoginInfo.class);
                    MyApp app = (MyApp) getApplication();
                    app.setLoginInfo(loginInfo);
                    int errorcode = loginInfo.getErrorcode();
                    if (errorcode == 200) {
                        SharedPreferences preferences = getSharedPreferences("autoLogin", MODE_PRIVATE);
                        SharedPreferences.Editor edit = preferences.edit();
                        edit.putString("userId", userId);
                        edit.putString("userName", userName);
                        edit.putString("account", "");
                        edit.putString("password", "");
                        edit.commit();
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel(Platform platform, int i) {
    }

    @Override
    protected void onDestroy() {
        ShareSDK.stopSDK();
        super.onDestroy();
    }
}
